import { networkStats } from "systeminformation";

function createNetworkSpeedMonitor() {
  let previousStats = {};

  async function getNetworkSpeed() {
    try {
      const currentStats = await networkStats();
      let totalDownloadSpeed = 0; // 总下载速度
      let totalUploadSpeed = 0; // 总上传速度

      currentStats.forEach((iface) => {
        if (previousStats[iface.iface]) {
          const downloadedBytes =
            iface.rx_bytes - previousStats[iface.iface].rx_bytes; // 下载字节数
          const uploadedBytes =
            iface.tx_bytes - previousStats[iface.iface].tx_bytes; // 上传字节数

          const downloadSpeed = Number(
            (((downloadedBytes / 1000) * 1000) / 1024).toFixed(2),
          ); // 下载速度，单位 KB/s
          const uploadSpeed = Number(
            (((uploadedBytes / 1000) * 1000) / 1024).toFixed(2),
          ); // 上传速度，单位 KB/s

          totalDownloadSpeed += downloadSpeed; // 累加总下载速度
          totalUploadSpeed += uploadSpeed; // 累加总上传速度
        }
      });

      // 更新 previousStats
      previousStats = currentStats.reduce((acc, iface) => {
        acc[iface.iface] = iface;
        return acc;
      }, {});

      return {
        download: totalDownloadSpeed,
        upload: totalUploadSpeed,
      };
    } catch (error) {
      console.error("Error fetching network stats:", error);
      return { download: 0, upload: 0 }; // 如果出错，返回默认值
    }
  }

  return getNetworkSpeed;
}

// 创建网络监控实例
const getNetworkSpeed = createNetworkSpeedMonitor();

// 使用示例
setInterval(async () => {
  const speeds = await getNetworkSpeed();
  console.log(speeds); // { download: 0, upload: 0 }
}, 2000);
